package 知识点复习.异步回调.异步任务的串行执行;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

public class ThenComposeDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {
            @Override
            public Long get() {
                long firstStep = 10 + 10;
                System.out.println(Thread.currentThread().getName() + ":first out is " + firstStep);
                return firstStep;
            }
        }).thenCompose(new Function<Long, CompletionStage<Long>>() {
            @Override
            public CompletionStage<Long> apply(Long firstStepOut) {
                //将第二个任务所要调用的普通异步方法包装成一个CompletionState异步实例
                return CompletableFuture.supplyAsync(new Supplier<Long>() {
                    //两个任务所要调用的普通异步方法
                    @Override
                    public Long get() {
                        long secondStep = firstStepOut * 2;
                        System.out.println(Thread.currentThread().getName() + ":second Step out is " + secondStep);
                        return secondStep;
                    }
                });
            }
        });
        Long result = future.get();
        System.out.println(Thread.currentThread().getName() + ":out is " + result);
    }
}
